package com.example.controller;

import com.example.common.Result;
import com.example.exception.CustomException;
import com.example.pojo.Account;
import com.example.pojo.LoginResponse;
import com.example.service.AdminService;
import com.example.service.OwnerService;
import com.example.service.UserService;
import com.example.util.ThreadLocalUtil;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/web")
public class WebController {

    @GetMapping("/hello")
    public Result hello(){
        throw new CustomException("400","自定义异常");

    }

    @Resource
    private AdminService adminService;

    @Resource
    private UserService userService;

    @Resource
    private OwnerService ownerService;

    /**
     * 登录
     * @param account
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Account account) {
        LoginResponse loginResponse = null;
        String token = null;


        if ("admin".equals(account.getRole())){
            //管理员登录
            loginResponse = adminService.login(account);
        }else if ("user".equals(account.getRole())){
            //用户登录
            loginResponse = userService.login(account);
        }else if ("owner".equals(account.getRole())){
            //房东登录
            loginResponse = ownerService.login(account);
        }else {
            throw new CustomException("500","角色不存在");
        }
        return Result.success(loginResponse);
    }

    /**
     * 修改密码
     * @param account
     * @return
     */
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody Account account, @RequestHeader("Authorization") String token) {
        Account result = null;

        if ("admin".equals(account.getRole())){
            //管理员修改密码
            adminService.updatePassword(account,token);
        }else if ("user".equals(account.getRole())){
            //用户修改密码
            userService.updatePassword(account,token);
        }else if ("owner".equals(account.getRole())){
            //用户修改密码
           ownerService.updatePassword(account,token);
        }else {
            throw new CustomException("500","角色不存在");
        }
        return Result.success(result);
    }

    @GetMapping("/userInfo")
    public Result userInfo() {
       return Result.success(ThreadLocalUtil.get());
    }


}
